const BASE_URL = 'https://hellodam.website:7049'

// 请求工具函数
function request(url, options = {}) {
  const config = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      ...options.headers
    },
    ...options
  }

  // 添加认证token
  const token = localStorage.getItem('admin_token')
  if (token) {
    config.headers['token'] = `${token}`
  }

  if (config.method !== 'GET' && options.data) {
    config.body = JSON.stringify(options.data)
  }

  return fetch(BASE_URL + url, config)
    .then(response => {
      if (!response.ok) {
        // 如果是401未授权，清除token并跳转到登录页
        if (response.status === 401) {
          localStorage.removeItem('admin_token')
          localStorage.removeItem('admin_user')
          window.location.reload()
        }
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      return response.json()
    })
    .catch(error => {
      console.error('API request failed:', error)
      throw error
    })
}

export { request, BASE_URL }